<?php
/**
* エラーチェッククラス
**/
require_once( '../system/Class_M_DAO.php' );
class Class_AFCS_DM extends Class_M_DAO {


	protected $_table = "M_COST_DM_COUNT";
	

	protected $_pkey = "id";
	

	//あとで投函日にする
	 protected $_order = "dm_date";
	 
	
	 public function search($where ,&$page  ,$year4, $aja_cd = NULL, $shop_cd2 = NULL ){
	 	
	 	$table_dm_cnt = " select  aa.matrix_cd, aa.dm_no from    M_COST_DM_COUNT  aa " .
	 		" inner join  M_MATRIX_TERM  bb  on aa.matrix_cd = bb.matrix_cd " ;
	 		
		if (!empty($aja_cd)) {
			$table_dm_cnt = $table_dm_cnt. " inner join  (select shop_cd from  M_AJAREKS a inner join M_LOGIN b on  a.userid = b.id  " .
			" where b.login_id = '{$aja_cd}')  aja on aa.shop_cd = aja.shop_cd " ;
		}
	 	
	 	$table_dm_cnt = $table_dm_cnt." WHERE bb.year4= {$year4}  ";
	 	
	 	if  (!empty($shop_cd2)) {
	 		$table_dm_cnt = $table_dm_cnt." and shop_cd = '{$shop_cd2}'" ;
	 	}
		
	 	$table_dm_cnt = $table_dm_cnt."group by   matrix_cd, dm_no ";
	 	$join_table_dm_cnt = "left join";
	 	if ( (!empty($aja_cd)) || (!empty($shop_cd2)) ) {
	 		$join_table_dm_cnt = "inner join";
	 	}
		$sqlfrom = " from M_COST_DM a {$join_table_dm_cnt} ({$table_dm_cnt}) b on a.matrix_cd = b.matrix_cd AND a.dm_no = b.dm_no " ;
		
		//部数テーブル
		$table_count = " select   aa.matrix_cd, aa.dm_no, sum(count) as shop_count  from    M_COST_DM_COUNT  aa " .
	 		" inner join  M_MATRIX_TERM  bb  on aa.matrix_cd = bb.matrix_cd WHERE bb.year4= {$year4} group by   matrix_cd, dm_no " ;
	 	
		$sql = "SELECT a.*,c.shop_count ".$sqlfrom. " left join ($table_count) c on a.matrix_cd = c.matrix_cd AND a.dm_no = c.dm_no ";
		$sqlcnt = "SELECT COUNT(*) AS cnt ".$sqlfrom;
		
		return  parent::search($where ,$page ,$sql,$sqlcnt);

	}

//	 public function search_csv($where  ){	
//		$sql = "SELECT a.*,b.ins_co_name,(select  user_name FROM {$this->_table} where  id  = a.u_user) as m_user_name from {$this->_table} a ";
//		$sql = $sql." LEFT JOIN  M_INS_CO b ON a.ins_co_cd = b.ins_co_cd ";
//		$page = null;
//		return  parent::search($where ,$page ,$sql);
//	}
	
}

?>